<?php

namespace app\admin\model;

use think\Model;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;


class AliYunSmsModel extends Model
{


    /**
     * 发送短信：短信模板CODE：久久金短信（短信通知）  SMS_217010045
     * @param string $phone;手机号，多个以英文逗号隔开
     * @param string $SignName;
     * @param string $TemplateCode;短信模板code
     * @param array $TemplateParam;模板参数
     * 不同手机号码，相同短信内容发送，最大一个批次发送100条
     */
    public static function sendSms($phone,$TemplateParam,$TemplateCode='',$SignName='',$accessKeyId="",$accessKeySecret="",$sendDataLimit=1000){
        $config=config();
        $conf=[];
        if(isset($config['sms'])&&$config['sms']&isset($config['sms']['ali_yun_sms_channel'])&&$config['sms']['ali_yun_sms_channel']){
            $conf=$config['sms']['ali_yun_sms_channel'];
        }
        if($accessKeyId==''||!$accessKeyId){
            if(isset($conf['accesskeyid'])&&$conf['accesskeyid']){
                $accessKeyId = $conf['accesskeyid'];
            }else{
                return ['code'=>403,'msg'=>"接口对接API平台缺少相关配置参数accesskeyid"];
            }
        }
        if($accessKeySecret==''||!$accessKeySecret){
            if(isset($conf['accesskeysecret'])&&$conf['accesskeysecret']){
                $accessKeySecret = $conf['accesskeysecret'];
            }else{
                return ['code'=>403,'msg'=>"接口对接API平台缺少相关配置参数accesskeysecret"];
            }
        }
        if($sendDataLimit>0&&is_numeric($sendDataLimit)&&$sendDataLimit){
            $phone_arr=explode(',',$phone);
            if(count($phone_arr)>$sendDataLimit){
                return ['code'=>403,'msg'=>"接口对接API平台短信配置限制最多只能批量发送".$sendDataLimit."条"];
            }
        }
        if(empty($TemplateCode)){
            if(empty($conf['sms_code'])||isset($conf['sms_code'])&&!$conf['sms_code']){
                return ['code'=>403,'msg'=>"接口对接API平台缺少签名配置参数sms_code"];
            }
            $TemplateCode=$conf['sms_code'];
        }
        if(empty($SignName)){
            if(empty($conf['sms_autograph'])||isset($conf['sms_autograph'])&&!$conf['sms_autograph']){
                return ['code'=>403,'msg'=>"接口对接API平台缺少签名配置参数sms_autograph"];
            }
            $SignName=$conf['sms_autograph'];
        }
        $params = array ();
        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $phone;
        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = $SignName;
        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $TemplateCode;
        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = $TemplateParam;
        // fixme 可选: 设置发送短信流水号
//        $params['OutId'] = "abcdefgh";
        // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
//        $params['SmsUpExtendCode'] = '1234567';
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        AlibabaCloud::accessKeyClient($accessKeyId ,$accessKeySecret)
            ->regionId('cn-hangzhou') // replace regionId as you need
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' =>array_merge($params, array(
                        "RegionId" => "cn-hangzhou"
                    )) ,
                ])
                ->request();
            $res=$result->toArray();
            if($res['Code']==="OK"){
                $aliYunRes = ['code'=>200,'data'=>$res,'msg'=>'接收成功!'];
            }else{
                $aliYunRes = ['code'=>403,'data'=>$res,'msg'=>$res['Message']];
            }
        } catch (ClientException $e) {
            $aliYunRes = ['code'=>400,'msg'=>$e->getErrorMessage()];
        } catch (ServerException $e) {
            $aliYunRes = ['code'=>401,'msg'=>$e->getErrorMessage()];
        }
        return $aliYunRes; //结果返回
    }

    /**
     * @param $phone;手机号
     * @param $SignName;签名
     * @param $TemplateCode;短信模板code
     * @param array $TemplateParam;模板参数
     * @param string $accessKeyId;短信配置 -阿里云短信账户名
     * @param string $accessKeySecret;短信配置 -阿里云短信账户密码
     * @param int $sendDataLimit;短信配置 -阿里云短信账户发送数量限制
     * @return array
     * 批量发送短信:不同手机号码，不同短信内容发送，最大一个批次发送100条
     */
    public static function sendBatchSms($phone,$SignName, $TemplateParam=array(),$TemplateCode='',$accessKeyId="",$accessKeySecret="",$sendDataLimit=100,$SmsUpExtendCodeJson=[]) {
        $config=config();
        $conf=[];
        if(isset($config['sms'])&&$config['sms']&isset($config['sms']['ali_yun_sms_channel'])&&$config['sms']['ali_yun_sms_channel']){
            $conf=$config['sms']['ali_yun_sms_channel'];
        }
        if($accessKeyId==''||!$accessKeyId){
            if(isset($conf['accesskeyid'])&&$conf['accesskeyid']){
                $accessKeyId = $conf['accesskeyid'];
            }else{
                return ['code'=>403,'msg'=>"接口对接API平台缺少相关配置参数accesskeyid"];
            }
        }
        if($accessKeySecret==''||!$accessKeySecret){
            if(isset($conf['accesskeysecret'])&&$conf['accesskeysecret']){
                $accessKeySecret = $conf['accesskeysecret'];
            }else{
                return ['code'=>403,'msg'=>"接口对接API平台缺少相关配置参数accesskeysecret"];
            }
        }
        if(empty($TemplateCode)){
            if(empty($conf['sms_code'])||isset($conf['sms_code'])&&!$conf['sms_code']){
                return ['code'=>403,'msg'=>"接口对接API平台缺少签名配置参数sms_code"];
            }
            $TemplateCode=$conf['sms_code'];
        }
        if($sendDataLimit>0&&is_numeric($sendDataLimit)&&$sendDataLimit){
            if(count($phone)>$sendDataLimit){
                return ['code'=>403,'msg'=>"接口对接API平台短信配置限制最多只能批量发送".$sendDataLimit."条"];
            }
        }
        $params = array ();
        // 必填:待发送手机号。支持JSON格式的批量调用，批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        /**
         * array(
        "1500000000",
        "1500000001",
        )
         */
        $params["PhoneNumberJson"] =json_encode($phone, JSON_UNESCAPED_UNICODE);
        // 必填:短信签名-支持不同的号码发送不同的短信签名
        /*
         * array(
            "云通信",
            "云通信"
                )
         */
        $params["SignNameJson"] =json_encode($SignName, JSON_UNESCAPED_UNICODE);
        // 必填:短信模板-可在短信控制台中找到
        $params["TemplateCode"] = $TemplateCode;
//        // fixme 可选: 设置发送短信流水号
//        $params['OutId'] = json_encode(['12133','21244'], JSON_UNESCAPED_UNICODE);
        //上行短信扩展码，JSON数组格式。无特殊需要此字段的用户请忽略此字段。 ["90999","90998"]
        if(count($SmsUpExtendCodeJson)){
//            $params["SmsUpExtendCodeJson"] =json_encode(["90999","90998"], JSON_UNESCAPED_UNICODE);
            $params["SmsUpExtendCodeJson"] =json_encode($SmsUpExtendCodeJson, JSON_UNESCAPED_UNICODE);
        }
        // 必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        /*
         * array(
             array(
                 "name" => "Tom",
                 "code" => "123",
             ),
             array(
                 "name" => "Jack",
                 "code" => "456",
             ),
         )
         */
        $params["TemplateParamJson"] = json_encode($TemplateParam, JSON_UNESCAPED_UNICODE);
        AlibabaCloud::accessKeyClient($accessKeyId ,$accessKeySecret)
            ->regionId('cn-hangzhou') // replace regionId as you need
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendBatchSms')
                ->method('POST')
                ->options([
                    'query' =>array_merge($params, array(
                        "RegionId" => "cn-hangzhou"
                    )) ,
                ])
                ->request();
            $res=$result->toArray();
            if($res['Code']==="OK"){
                $aliYunRes = ['code'=>200,'data'=>$res,'msg'=>'接收成功!'];
            }else{
                $aliYunRes = ['code'=>403,'data'=>$res,'msg'=>$res['Message']];
            }
        } catch (ClientException $e) {
            $aliYunRes = ['code'=>400,'msg'=>$e->getErrorMessage()];
        } catch (ServerException $e) {
            $aliYunRes = ['code'=>400,'msg'=>$e->getErrorMessage()];
        }
        return $aliYunRes;   //结果返回
    }

}